package blockchain.block;

import java.util.Date;

// 区块类
public class Block {
    private String hash; // 当前区块哈希值
    private final String previousHash; // 上⼀个区块哈希值
    public String data; // 农产品数据（JSON格式）
    private final long timeStamp; // 时间戳
    // 构造函数
    public Block(String data, String previousHash) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = new Date().getTime();
        this.hash = calculateHash(); // 计算当前哈希
    }
    public Block(String data) {
        this.data = data;
        this.previousHash = "";
        this.timeStamp = new Date().getTime();
        this.hash = calculateHash();
    }
    // 计算SHA-256哈希
    public String calculateHash() {
        String input = previousHash + timeStamp + data;
        return Sha.Sha256(input);
    }

    public String getHash() { return hash = calculateHash(); }  //每次查询都刷新哈希值
    public String getPreviousHash() { return previousHash; }
    public String getData() { return data; }
    public long getTimeStamp() { return timeStamp; }
}
